<?php
namespace app\home\controller;

// 引入TP基类控制器
use think\Controller;
use think\Db;


class Index extends Controller
{
    // 客户模型
    protected $BusinessModel = null;
    protected $SourceModel = null;

    // 初始化
    public function _initialize()
    {
        $this->BusinessModel = model('business.Business');
        $this->SourceModel = model('business.Source');
    }

    public function index()
    {
        return $this->fetch();
    }

    // 注册
    public function register()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $repass = $this->request->param('repass', '', 'trim');

            if ($password != $repass) {
                $this->error("两次输入的密码不匹配！");
            }

            // 生成密码盐
            $salt = build_ranstr();

            $password = md5($password . $salt);

            // 相当于默认写定
            $source = $this->SourceModel->where('name', '云课堂')->value('id');
            $data = [
                'mobile' => $mobile,
                'password' => $password,
                'salt' => $salt,
                'invitecode' => build_ranstr(),
                'sourceid' => $source
            ];

            $res = $this->BusinessModel->validate('common/business/Business')->save($data);

            if ($res === false) {
                $this->error($this->BusinessModel->getError());
            } else {
                $this->success('注册成功', url('/home/index/login'));
            }
        }

        $this->view->engine->layout(false);
        return $this->fetch();
    }

    // 登录
    public function login()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $res = $this->BusinessModel->where('mobile', $params['mobile'])->find();
            if (!$res) {
                $this->error('该用户未注册');
            }
            $password = md5($params['password'] . $res['salt']);
            if ($password != $res['password']) {
                $this->error('密码错误');
            }

            $data = [
                'id' => $res['id'],
                'mobile' => $res['mobile'],
                'nickname' => $res['nickname']
            ];
            cookie('business', $data);

            $this->success('登录成功', url('/home/business/index'));
        }

        // 当前页面关闭了模板布局
        $this->view->engine->layout(false);
        return $this->fetch();
    }

}